package com.example.jobback.websocket.config;

import com.example.jobback.websocket.intercept.WebSocketHandshakeInterceptor;
import jakarta.servlet.ServletContext;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
 * @ClassName: WebSocketConfigurator
 * @Description: websocket配置类
 * @Author: lhb
 * @Date: 2025/5/28
 */
@Component
@Configuration
public class WebSocketConfigurator extends ServerEndpointConfig.Configurator implements ServletContextInitializer {

    private static WebSocketHandshakeInterceptor interceptor;

    @Autowired
    public void setInterceptor(WebSocketHandshakeInterceptor interceptor) {
        WebSocketConfigurator.interceptor = interceptor;
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    
    /**
     * @Description: 重写握手方法
     * @param sec
     * @param request
     * @param response 
     * @return void
     * @Author lhb
     * @CreateTime 2025/5/29 22:21
     */
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        try {
            interceptor.handleHandshake(sec, request, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 设置文本消息缓冲区
     * @param servletContext 
     * @return void
     * @Author lhb
     * @CreateTime 2025/5/29 22:25
     */
    @Override
    public void onStartup(ServletContext servletContext){
        // 设置文本消息缓冲区大小为10mb
        servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize", "10485760");
        // 设置二进制消息缓冲区大小为10mb
        servletContext.setInitParameter("org.apache.tomcat.websocket.binaryBufferSize", "10485760");
    }

}
